package chapter5_基础构建模块.阻塞方法与中断方法;

public class RestoreInterrupt implements Runnable {

    @Override
    public void run() {
        while (true) {
            System.out.println("运行中");
            // 检测中断标志位
            if (Thread.currentThread().isInterrupted()) {
                System.out.println("检测到线程被中断了");
                break;
            }
            doSomething();
        }
    }

    private void doSomething() {
        try {
            // 会抛出InterruptedException受检异常，说明是一个阻塞方法
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            System.out.println("doSomething 检测到中断异常了，此时中断标志位:" + Thread.currentThread().isInterrupted());
            e.printStackTrace();
            // 通过Thread.currentThread().interrupt()恢复中断状态，从而被上层代码检测到，并进行相应逻辑处理
            // 如果不恢复则代码会在while中一直运行，代码无法正常退出while循环
            Thread.currentThread().interrupt();
            System.out.println("doSomething 恢复中断标志位后，此时中断标志位:" + Thread.currentThread().isInterrupted());
        }
    }

    public static void main(String[] args) {
        Thread thread = new Thread(new RestoreInterrupt());
        thread.start();

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            System.out.println("????????");
            e.printStackTrace();
        }
        // 5秒后手动中断该线程
        thread.interrupt();

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            System.out.println("????????");
            e.printStackTrace();
        }
        // 5秒后再次手动中断该线程
        thread.interrupt();
    }
}
